import { AIMessage, UserMessage, ChatConfig } from '../types';

export class AIChatWidget {
    private container: HTMLElement;
    private config: ChatConfig;
    private chatBody: HTMLElement;
    private userInput: HTMLInputElement;
    private sendButton: HTMLButtonElement;

    constructor(containerId: string, config: ChatConfig) {
        this.container = document.getElementById(containerId) as HTMLElement;
        this.config = {
            apiUrl: config.apiUrl || 'https://api.deepseek.com/v1/chat/completions',
            apiKey: config.apiKey,
            systemPrompt: config.systemPrompt || '你是AI助手，负责回答用户的问题。请提供专业、友好的回答。',
            theme: config.theme || 'light',
            placeholder: config.placeholder || '请输入您的问题...',
            welcomeMessage: config.welcomeMessage || '您好！我是AI助手，很高兴为您服务。请问有什么可以帮助您的吗？'
        };
        this.initializeUI();
        this.bindEvents();
    }

    private initializeUI(): void {
        this.container.innerHTML = `
            <div class="ai-chat-widget ${this.config.theme}">
                <div class="ai-chat-header">
                    <div class="ai-avatar">AI</div>
                    <div class="ai-name">AI助手</div>
                </div>
                <div class="ai-chat-body" id="${this.container.id}-body"></div>
                <div class="ai-chat-footer">
                    <input type="text" class="ai-input" placeholder="${this.config.placeholder}" />
                    <button class="ai-send-btn">➤</button>
                </div>
            </div>
        `;

        this.chatBody = document.getElementById(`${this.container.id}-body`) as HTMLElement;
        this.userInput = this.container.querySelector('.ai-input') as HTMLInputElement;
        this.sendButton = this.container.querySelector('.ai-send-btn') as HTMLButtonElement;

        // 添加欢迎消息
        this.addAIMessage(this.config.welcomeMessage);
    }

    private bindEvents(): void {
        this.sendButton.addEventListener('click', () => this.sendMessage());
        this.userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        });
    }

    private async sendMessage(): Promise<void> {
        const message = this.userInput.value.trim();
        if (!message) return;

        // 添加用户消息
        this.addUserMessage(message);
        this.userInput.value = '';

        // 创建AI消息容器
        const aiMessageContainer = this.createAIMessageContainer();

        try {
            const response = await fetch(this.config.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.config.apiKey}`,
                    'Accept': 'text/event-stream'
                },
                body: JSON.stringify({
                    model: 'deepseek-chat',
                    messages: [
                        {
                            role: 'system',
                            content: this.config.systemPrompt
                        },
                        {
                            role: 'user',
                            content: message
                        }
                    ],
                    temperature: 0.7,
                    max_tokens: 500,
                    stream: true
                })
            });

            if (!response.ok) {
                throw new Error(`API调用失败: ${response.status}`);
            }

            const reader = response.body!.getReader();
            const decoder = new TextDecoder();

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n');

                for (const line of lines) {
                    if (line.trim() === '' || !line.startsWith('data:')) continue;
                    const data = line.slice(5).trim();
                    if (data === '[DONE]') continue;

                    try {
                        const parsed = JSON.parse(data);
                        const content = parsed.choices[0].delta.content || '';
                        if (content) {
                            aiMessageContainer.textContent += content;
                            this.scrollToBottom();
                        }
                    } catch (error) {
                        console.error('解析响应数据时出错:', error);
                    }
                }
            }
        } catch (error) {
            console.error('调用API时出错:', error);
            aiMessageContainer.textContent = '抱歉，我暂时无法回答您的问题。请稍后再试。';
        }

        this.scrollToBottom();
    }

    private addUserMessage(message: string): void {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message user-message';
        messageDiv.innerHTML = `
            <div class="message-bubble user-bubble">
                ${this.escapeHtml(message)}
            </div>
        `;
        this.chatBody.appendChild(messageDiv);
        this.scrollToBottom();
    }

    private createAIMessageContainer(): HTMLElement {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message ai-message';
        
        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = 'message-bubble ai-bubble';
        messageDiv.appendChild(bubbleDiv);
        
        this.chatBody.appendChild(messageDiv);
        return bubbleDiv;
    }

    private addAIMessage(message: string): void {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message ai-message';
        messageDiv.innerHTML = `
            <div class="message-bubble ai-bubble">
                ${this.escapeHtml(message)}
            </div>
        `;
        this.chatBody.appendChild(messageDiv);
        this.scrollToBottom();
    }

    private scrollToBottom(): void {
        this.chatBody.scrollTop = this.chatBody.scrollHeight;
    }

    private escapeHtml(text: string): string {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}